package com.wantup.demo03xd;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/7/3 10:22
 * <p>
 * <p>
 * ReentrantReadWriteLock 案例
 * 读写锁 有三种使用特性。
 */
public class ReentrantReadWriteLockDemo {

    private int num = 0;
    private int j = 0;

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    Lock readLock = readWriteLock.readLock();
    Lock writeLock = readWriteLock.writeLock();


    public void out() {
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " --- num 的值是 " + num + " --- j 的值是 " + j);
        } finally {
            readLock.unlock();
        }
    }

    public void add() {
        writeLock.lock();
        try {
            num++;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            j++;

        } finally {
            writeLock.unlock();
        }
    }


    public static void main(String[] args) {
        ReentrantReadWriteLockDemo demo = new ReentrantReadWriteLockDemo();
        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    demo.add();
                    demo.out();

                }
            }).start();

        }


    }


}
